﻿using System;
using JT.Data;
using JT.WEB.Areas.Identity.Data;
using JT.WEB.Models;
using JT.WEB.Models.Were;
using JT.WEB.Service;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace JT.WEB
{
    public class Startup
    {
        public Startup(IConfiguration configuration, IHostEnvironment env)
        {
            Configuration = configuration;
            GlobalTo.Configuration = configuration;
            GlobalTo.HostEnvironment = env;
            //try
            //{
            //    //无创建，有忽略
            //    using var db = new Data.ContextBase();
            //    db.Database.EnsureCreated();
            //}
            //catch (System.Exception)
            //{
            //}
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                //cookie存储需用户同意，欧盟新标准，暂且关闭，否则用户没同意无法写入.
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            //跨域，用法：[EnableCors("any")]
            services.AddCors(options =>
            {
                options.AddPolicy("any", builder =>
                {
                    builder.AllowAnyOrigin() //允许任何来源的主机访问
                        .AllowAnyMethod()
                        .AllowAnyHeader();
                });
            });
            var connection = Configuration.GetConnectionString("DefaultContextConnection");
            services.AddDbContext<ContextWere>(options => options.UseMySql(connection));
            services.AddDbContext<ContextNews>(options => options.UseMySql(connection));
            services.AddDbContext<ContextBase>(options => options.UseMySql(connection, b => b.MigrationsAssembly("JT.WEB")));
            services.AddDbContext<ContextUser>(options => options.UseMySql(connection));



            services.AddIdentity<JTWEB3User, IdentityRole>()
                .AddEntityFrameworkStores<ContextUser>().AddDefaultUI().AddDefaultTokenProviders();

            services.Configure<IdentityOptions>(options =>
            {
                // Password settings.
                options.Password.RequireDigit = false; //需要数字
                options.Password.RequireLowercase = false; //需要小写字母
                options.Password.RequireNonAlphanumeric = false; //需要非字母与数字符号的
                options.Password.RequireUppercase = false; //需要大写字母
                options.Password.RequiredLength = 1; //需要长度
                options.Password.RequiredUniqueChars = 1; //需要数字

                // Lockout settings.
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); //五次输入错误锁定
                options.Lockout.MaxFailedAccessAttempts = 5; //五次输入错误锁定
                options.Lockout.AllowedForNewUsers = true;

                // User settings.
                options.User.AllowedUserNameCharacters =
                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                options.User.RequireUniqueEmail = false;
                // Default SignIn settings.
                options.SignIn.RequireConfirmedEmail = false;
                options.SignIn.RequireConfirmedPhoneNumber = false;
            });

            services.ConfigureApplicationCookie(options =>
            {
                // Cookie settings
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

                options.LoginPath = "/Identity/Account/Login";
                options.AccessDeniedPath = "/Identity/Account/AccessDenied";
                options.SlidingExpiration = true;
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("仅限管理员", policy => policy.RequireUserName("admin@qq.com"));
            });
            services.AddTransient<BannerService>();
            services.AddTransient<ContextNews>();
            services.AddTransient<NewsService>();
            services.AddTransient<CommentService>();
            services.AddTransient<IWereHouseService, WereHouseService>();
            services.AddTransient<IUserCenter, UserCenterService>();


            services.AddControllersWithViews();
            services.AddRazorPages().AddRazorRuntimeCompilation();


        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection(); //重定向

            //静态资源允许跨域
            app.UseStaticFiles(new StaticFileOptions()
            {
                OnPrepareResponse = (x) =>
                {
                    x.Context.Response.Headers.Add("access-control-allow-origin", "*");
                }
            });
            //跨域
            app.UseCors("any");

            app.UseCookiePolicy();
            app.UseRouting();


            app.UseAuthentication(); //身份验证
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllerRoute(
                    name: "areaRoute",
                    pattern: "{area:exists}/{controller=NewsHome}/{action=Index}/{id?}");
                endpoints.MapControllerRoute(
                    name: "areaRoute",
                    pattern: "{area:exists}/{controller=Message}/{action=Index}/{id?}");
                endpoints.MapAreaControllerRoute(
                    name: "JtSiteAdmin",
                    areaName: "JtSiteAdmin",
                    pattern: "{controller=Message}/{action=Index}/{id?}");
                endpoints.MapControllerRoute(
                   name: "areaRoute",
                   pattern: "{area:exists}/{controller=News}/{action=Index}/{id?}");
                endpoints.MapAreaControllerRoute(
                    name: "NewsManage",
                    areaName: "NewsManage",
                    pattern: "{controller=News}/{action=Index}/{id?}"
                );

                endpoints.MapRazorPages();
            });

        }
    }
}